﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.IO;
using System.Data.SqlClient;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Socket serverSocket = null;
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "未联机")
            {
                try
                {
                    button1.Text = "等待连接";
                    button1.BackColor = Color.Yellow;
                    serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPAddress ipAddress = IPAddress.Parse(comboBox1.Text);//获取IP地址
                    int port = Convert.ToInt32(textBox2.Text);          //获取端口号
                    IPEndPoint endPoint = new IPEndPoint(ipAddress, port); //第一个参数为要设置的IP地址，第二参数为端口号
                    serverSocket.Bind(endPoint);
                    serverSocket.Listen(10); //参数为最大监听的用户数

                    if (!bgw_connect.IsBusy)
                    {
                        bgw_connect.RunWorkerAsync();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "警告");
                }
            }
            else
            {
                try
                {
                    button1.Text = "未联机";
                    button1.BackColor = Color.FromArgb(255, 1, 255);
                    // serverSocket.BeginDisconnect(false,null,null);
                    //bgw_connect.CancelAsync();
                    // ClientSocket.Close();
                    serverSocket.Close();
                    //ClientSocket = null;
                    serverSocket.Dispose();
                   // ClientSocket.Close();
                   // ClientSocket.Dispose();
                }
                catch (Exception)
                {

                  //  throw;
                }
            

            }

        }
        Socket ClientSocket = null;

        private void bgw_connect_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                try
                {
                     ClientSocket = serverSocket.Accept();
                    //ClientSocket = serverSocket.BeginAccept();
                
                    Thread thr = new Thread(ReceiveClientMsg);
                    thr.IsBackground = true;
                    thr.Start(ClientSocket);
                    //thr.Start();
                    this.Invoke(new Action(() =>
                    {
                        button1.Text = "已联机";
                        button1.BackColor = Color.FromArgb(0,255,0);

                    }));

                }
                catch (Exception ex)
                {
                    // listenThread.Abort(ex.Message);
                  //  MessageBox.Show(ex.ToString());
                }
            }
        }
        private void ReceiveClientMsg(object clientSocket)
        {
            Socket client = clientSocket as Socket;
            while (true)
            {
                try
                {
                    byte[] recBuffer = new byte[1024 * 1024 * 20];
                    int length = client.Receive(recBuffer);
                    if (length == 0)
                    {
                        string str1 = client.RemoteEndPoint.ToString();
                        this.Invoke(new Action(() =>
                        {

                            client.Close();

                        }));
                        break;
                    }
                    else
                    {
                        string msg = Encoding.Default.GetString(recBuffer, 0, length);
                        this.Invoke(new Action(() =>
                        {
                            textBox3.AppendText(msg + "\r\n" );

                        }));
                    }
                }
                catch { }
            }

        }
        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox4.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            textBox3.Clear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox4.Clear();
        }

        /// <summary>
        /// 关闭窗口断开远程连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //System.Environment.Exit(0);
            try
            {
                //MySocket.Close();
              //  MySocket.BeginDisconnect(true, null, null);

            }
            catch { }

            //MySocket.Dispose();

        }
        /// <summary>
        /// 定时发送指令
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            string str = textBox4.Text;
            try
            {
                if (checkBox3.Checked)
                {
                   // timer1.Start();
                    timer1.Interval = Convert.ToUInt16(comboBox6.Text, 10);
                    if (str.Length > 0)
                    {
                        byte[] buffer = new byte[1024 * 8];
                        buffer = Encoding.Default.GetBytes(str);
                        ClientSocket.Send(buffer);
                    }
                   else if (checkBox4.Checked)
                    {
                        string str1 = textBox5.Text;
                        byte[] buffer = new byte[1024 * 8];
                        buffer = Encoding.Default.GetBytes(str1);
                        ClientSocket.Send(buffer);
                    }
                    else if (checkBox5.Checked)
                    {
                        string str2 = textBox6.Text;
                        byte[] buffer = new byte[1024 * 8];
                        buffer = Encoding.Default.GetBytes(str2);
                        ClientSocket.Send(buffer);
                    }

                }
               
            }

            catch { }

        }
        /// <summary>
        /// 窗口初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {

            string ip;
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        ip = IpEntry.AddressList[i].ToString();
                        comboBox1.Items.Add(ip);
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("获取本机IP出错:" + ex.Message);

            }
            //comboBox1.Text = "all connects";
            comboBox1.SelectedIndex = 0;
            comboBox6.Text = "1000";
            timer1.Start();
        }
        /// <summary>
        /// 发送事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox5.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox6.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox7.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox8.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox9.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }

        private void button11_Click(object sender, EventArgs e)
        {
            try
            {
                string str = textBox10.Text;
                byte[] buffer = new byte[1024 * 8];
                buffer = Encoding.Default.GetBytes(str);
                ClientSocket.Send(buffer);
            }
            catch { }
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            SaveFileDialog file = new SaveFileDialog();
            file.Filter = "C.File|*.c|所有文件|*.*";
            file.InitialDirectory = Application.StartupPath;
            if (file.ShowDialog() == DialogResult.OK)
            {
                string FileName = file.FileName;
                FileStream fs = new FileStream(FileName,FileMode.OpenOrCreate,FileAccess.Write);
                StreamWriter ws = new StreamWriter(fs);
                long str = fs.Length;
                fs.Seek(str,SeekOrigin.End);
                ws.WriteLine(textBox3.Text);
                ws.Close();
                fs.Close();
                MessageBox.Show("文件" + FileName + "保存成功");
            
            }

        }

        private void button12_Click(object sender, EventArgs e)
        {
            string connStr = "server=.;uid=sa;pwd=123456;database=test";
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = connStr;
            conn.Open();
            try
            {
                string sql = " insert into chat (date, content) values ('{0}' , '{1}')";
                string date = textBox3.Text;
                string date1 = textBox3.Text;
                int firsrindex = date.IndexOf(":");
                int lastrindex = date.IndexOf("108");
                date = date.Substring(0,firsrindex);
                date1 = date1.Substring(lastrindex,date1.Length - lastrindex);
                sql = string.Format(sql, date, date1);
                SqlCommand cmd = new SqlCommand(sql, conn);
                //执行SQL语句
                int returnvalue = cmd.ExecuteNonQuery();
                //判断SQL语句是否执行成功
                if (returnvalue != -1)
                {
                    MessageBox.Show("添加成功！");
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show("注册失败！" + ex.Message);
            }
        }

    }    
}



